import React, { useState, useEffect, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import { 
  ArrowLeft, 
  Send, 
  Image, 
  Mic, 
  Smile, 
  MoreVertical,
  Phone,
  Video
} from 'lucide-react';
import { useAuthStore, useChatStore } from '../stores';
import { apiService } from '../services/api';
import toast from 'react-hot-toast';
import { format } from 'date-fns';
import { zhCN } from 'date-fns/locale';
import type { ChatMessage } from '../types/api';

const ChatPage: React.FC = () => {
  const { matchId } = useParams<{ matchId: string }>();
  const navigate = useNavigate();
  const { user } = useAuthStore();
  const { 
    messages, 
    addMessage, 
    markAsRead, 
    setMessages 
  } = useChatStore();
  
  const [newMessage, setNewMessage] = useState('');
  const [isLoading, setIsLoading] = useState(true);
  const [isSending, setIsSending] = useState(false);
  const [matchUser, setMatchUser] = useState<any>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const inputRef = useRef<HTMLInputElement>(null);

  const matchIdNum = parseInt(matchId || '0');
  const chatMessages = messages[matchIdNum] || [];

  // 滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  useEffect(() => {
    scrollToBottom();
  }, [chatMessages]);

  // 获取聊天消息
  useEffect(() => {
    const fetchMessages = async () => {
      if (!user || !matchIdNum) return;

      try {
        const response = await apiService.getChatMessages(user.user_id, matchIdNum, 1, 50);
        if (response.code === 0) {
          setMessages(matchIdNum, response.data.messages);
          
          // 获取匹配用户信息
          const matchDetailResponse = await apiService.getMatchDetail(user.user_id, matchIdNum);
          if (matchDetailResponse.code === 0) {
            setMatchUser({
              nickname: matchDetailResponse.data.nickname,
              avatar: matchDetailResponse.data.avatar,
            });
          }
        }
      } catch (error) {
        console.error('Fetch messages error:', error);
        toast.error('获取聊天记录失败');
      } finally {
        setIsLoading(false);
      }
    };

    fetchMessages();
  }, [user, matchIdNum, setMessages]);

  // 标记消息为已读
  useEffect(() => {
    const markMessagesRead = async () => {
      if (!user || !matchIdNum) return;

      try {
        await apiService.markMessagesAsRead(user.user_id, matchIdNum);
        markAsRead(matchIdNum);
      } catch (error) {
        console.error('Mark messages read error:', error);
      }
    };

    markMessagesRead();
  }, [user, matchIdNum, markAsRead]);

  // 发送消息
  const handleSendMessage = async () => {
    if (!newMessage.trim() || !user || !matchIdNum || isSending) return;

    const messageContent = newMessage.trim();
    setNewMessage('');
    setIsSending(true);

    // 创建临时消息
    const tempMessage: ChatMessage = {
      message_id: Date.now(),
      user_id: user.user_id,
      match_id: matchIdNum,
      content: messageContent,
      msg_type: 1,
      created_at: new Date().toISOString(),
      is_read: false,
    };

    addMessage(matchIdNum, tempMessage);

    try {
      const response = await apiService.sendMessage({
        user_id: user.user_id,
        match_id: matchIdNum,
        content: messageContent,
        msg_type: 1,
      });

      if (response.code === 0) {
        // 更新消息ID
        const updatedMessage = { ...tempMessage, message_id: response.data.message_id };
        setMessages(matchIdNum, [
          ...chatMessages.filter(m => m.message_id !== tempMessage.message_id),
          updatedMessage
        ]);
      }
    } catch (error) {
      console.error('Send message error:', error);
      toast.error('发送消息失败');
      // 移除临时消息
      setMessages(matchIdNum, chatMessages.filter(m => m.message_id !== tempMessage.message_id));
    } finally {
      setIsSending(false);
    }
  };

  // 处理回车发送
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const formatMessageTime = (timeString: string) => {
    try {
      const date = new Date(timeString);
      const now = new Date();
      const diffInHours = (now.getTime() - date.getTime()) / (1000 * 60 * 60);
      
      if (diffInHours < 24) {
        return format(date, 'HH:mm', { locale: zhCN });
      } else {
        return format(date, 'MM-dd HH:mm', { locale: zhCN });
      }
    } catch {
      return '';
    }
  };

  if (isLoading) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="w-8 h-8 border-2 border-primary-500 border-t-transparent rounded-full animate-spin mx-auto mb-4"></div>
          <p className="text-gray-600">加载聊天记录中...</p>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* 聊天头部 */}
      <div className="bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <button
            onClick={() => navigate('/matches')}
            className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200"
          >
            <ArrowLeft size={20} />
          </button>
          
          <div className="flex items-center space-x-3">
            <img
              src={matchUser?.avatar || '/api/placeholder/40/40'}
              alt={matchUser?.nickname}
              className="w-10 h-10 rounded-full object-cover"
            />
            <div>
              <h2 className="font-semibold text-gray-900">{matchUser?.nickname || '用户'}</h2>
              <div className="flex items-center space-x-2 text-xs text-gray-500">
                <div className="w-2 h-2 bg-green-500 rounded-full"></div>
                <span>在线</span>
              </div>
            </div>
          </div>
        </div>

        <div className="flex items-center space-x-2">
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200">
            <Phone size={20} />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200">
            <Video size={20} />
          </button>
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200">
            <MoreVertical size={20} />
          </button>
        </div>
      </div>

      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto px-4 py-4 space-y-4">
        <AnimatePresence>
          {chatMessages.map((message) => {
            const isOwn = message.user_id === user?.user_id;
            return (
              <motion.div
                key={message.message_id}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -20 }}
                className={`flex ${isOwn ? 'justify-end' : 'justify-start'}`}
              >
                <div className={`max-w-xs lg:max-w-md ${isOwn ? 'order-2' : 'order-1'}`}>
                  <div
                    className={`px-4 py-2 rounded-2xl ${
                      isOwn
                        ? 'bg-primary-500 text-white rounded-br-md'
                        : 'bg-white text-gray-900 rounded-bl-md border border-gray-200'
                    }`}
                  >
                    <p className="text-sm">{message.content}</p>
                  </div>
                  <p className={`text-xs text-gray-500 mt-1 ${isOwn ? 'text-right' : 'text-left'}`}>
                    {formatMessageTime(message.created_at)}
                  </p>
                </div>
              </motion.div>
            );
          })}
        </AnimatePresence>
        <div ref={messagesEndRef} />
      </div>

      {/* 消息输入框 */}
      <div className="bg-white border-t border-gray-200 px-4 py-3">
        <div className="flex items-center space-x-3">
          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200">
            <Smile size={20} />
          </button>
          
          <div className="flex-1 flex items-center bg-gray-100 rounded-full px-4 py-2">
            <input
              ref={inputRef}
              type="text"
              value={newMessage}
              onChange={(e) => setNewMessage(e.target.value)}
              onKeyPress={handleKeyPress}
              placeholder="输入消息..."
              className="flex-1 bg-transparent outline-none text-sm"
              disabled={isSending}
            />
            <button className="p-1 hover:bg-gray-200 rounded-full transition-colors duration-200">
              <Image size={20} />
            </button>
          </div>

          <button className="p-2 hover:bg-gray-100 rounded-full transition-colors duration-200">
            <Mic size={20} />
          </button>

          <motion.button
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
            onClick={handleSendMessage}
            disabled={!newMessage.trim() || isSending}
            className="w-10 h-10 bg-primary-500 hover:bg-primary-600 disabled:opacity-50 disabled:cursor-not-allowed rounded-full flex items-center justify-center transition-colors duration-200"
          >
            <Send className="text-white" size={18} />
          </motion.button>
        </div>
      </div>
    </div>
  );
};

export default ChatPage;
